<template>
  <div class="dealerGoodsApply sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="经销商名称:">
              <el-select
                class="custom_select"
                v-model="query.dealersId"
                filterable
                remote
                remote-show-suffix 
                clearable 
                placeholder="请输入经销商名称查询"
                :remote-method="loadDealer">
                <el-option v-for="item in dealerList" :key="item.dealersId" :label="item.memberName" :value="item.dealersId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="审核状态:">
              <el-select v-model="query.applyStatus" placeholder="请选择" clearable>
                <el-option label="待审核" value="0" />
                <el-option label="通过" value="1" />
                <el-option label="驳回" value="2" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="show = true">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="经销商商品申请数据" icon="Histogram" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中">
        <el-table :data="dataList" max-height="493" border>
          <el-table-column label="序号" type="index" align="center" width="60"/>
          <el-table-column label="编号" prop="dealerCode" align="center" width="180"></el-table-column>
          <el-table-column label="姓名" prop="dealerName" align="center"></el-table-column>
          <el-table-column label="手机号" prop="phone" align="center"></el-table-column>
          <el-table-column label="状态" prop="applyStatus" align="center">
            <template #default="{row}">
              <el-tag v-if="row.applyStatus === 0" type="info">待审核</el-tag>
              <el-tag v-if="row.applyStatus === 1" type="success">通过</el-tag>
              <el-tag v-if="row.applyStatus === 2" type="danger">驳回</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="驳回理由" prop="rejectReason" align="center"></el-table-column>
          <el-table-column label="创建时间" prop="createdTime" align="center" width="170">
            <template #default="{row}">
              <span>{{ $date(row.createdTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="250">
            <template #default="{row}">
              <el-button type="primary" icon="View" link @click="toView(row)">详情</el-button>
              <el-divider v-if="row.applyStatus === 0" direction="vertical" />
              <el-button v-if="row.applyStatus === 0" type="success" icon="SuccessFilled" link @click="toExamine(row, true)">通过</el-button>
              <el-divider v-if="row.applyStatus === 0" direction="vertical" />
              <el-button v-if="row.applyStatus === 0" type="danger" icon="RefreshRight" link @click="toExamine(row, false)">驳回</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增、编辑弹窗 -->
    <el-dialog v-model="show" title="新增" top="10vh" width="45%" center draggable @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="default" label-position="right" label-width="125px">
        <el-form-item label="经销商:" prop="dealersId" required>
          <el-select
            v-model="form.dealersId"
            filterable
            remote
            remote-show-suffix 
            clearable 
            placeholder="请输入经销商名称查询"
            :remote-method="loadDealer">
            <el-option v-for="item in dealerList" :key="item.dealersId" :label="item.memberName" :value="item.dealersId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="商品申请规则:" prop="ruleId" required>
          <el-select v-model="form.ruleId" placeholder="请选择经销商注册规则" clearable>
            <el-option v-for="item in ruleList" :key="item.ruleId" :label="item.ruleName" :value="item.ruleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定商品:" prop="productIdList" required>
          <el-button type="primary" @click="toChooseGoods">选择商品</el-button>
          <el-table :data="bindGoods" max-height="493" border style="margin-top: 10px;">
            <el-table-column label="序号" type="index" align="center" width="60"/>
            <el-table-column label="商品名称" prop="name" align="center"></el-table-column>
            <el-table-column label="商品图片" prop="pic" align="center">
              <template #default="{row}">
                <div class="img-cell">
                  <el-image :src="row.pic + '?x-oss-process=image/resize,m_fill,h_40,w_40'"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="商品价格" prop="salePrice" align="center"></el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template #default="{$index}">
                <el-button type="danger" icon="delete" link @click="doDeleteBindGoods($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <el-dialog v-model="innerShow" title="商品选择" width="50%" append-to-body class="append-to-body-dialog">
        <el-form :model="goodsQuery" inline>
          <el-form-item label="商品名称:">
            <el-input v-model="goodsQuery.name" placeholder="请输入商品名称" clearable/>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" icon="Search" @click="loadGoods(1)">查询</el-button>
            <el-button type="primary" icon="Check" @click="doChooseGoods">选择</el-button>
          </el-form-item>
        </el-form>
        <el-table ref="tableRef" :data="goods" max-height="493" border>
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="商品名称" prop="name" align="center"></el-table-column>
          <el-table-column label="商品图片" prop="pic" align="center">
            <template #default="{row}">
              <div class="img-cell">
                <el-image :src="row.pic + '?x-oss-process=image/resize,m_fill,h_40,w_40'"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品价格" prop="salePrice" align="center"></el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="goodsQuery.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="goodsQuery.current" 
          :page-size="goodsQuery.size"
          :total="goodsQuery.total"
          @current-change="loadGoods"
          @size-change="goodsSizeChange">
        </el-pagination>
      </el-dialog>
      <template #footer>
        <el-button type="primary" size="default" @click="doSave">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-drawer 
      v-model="infoShow" 
      :with-header="false" 
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="false" 
      size="89.6%">
      <dealer-goods-apply-details :productApplyId="productApplyId" :dealersId="dealersId" @close="doChose"></dealer-goods-apply-details>
    </el-drawer>
  </div>
</template>

<script setup name="dealerGoodsApply">
  import dealerGoodsApplyDetails from './details.vue'
  import { 
    saveDealerGoodsApplyApi, 
    getDealerGoodsApplyListPagesApi, 
    updateDealerGoodsApplyStatusApi, 
    getDealerListApi, 
    getGoodsApplyRuleListApi, 
    // getDealerCanBindGoodsListPagesApi 
  } from '@/api/api'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  
  const formRef = ref(null)
  const tableRef = ref(null)

  const currentData = reactive({
    loading: false,
    show: false,
    innerShow: false,
    infoShow: false,
    query: {
      dealersId: '',
      applyStatus: '',
      current: 1,
      size: 20,
      total: 0
    },
    goodsQuery: {
      name: '',
      current: 1,
      size: 20,
      total: 0
    },
    form: {
      dealersId: '',
      ruleId: '',
      productIdList: []
    },
    examineForm: {
      productApplyId: '',
      dealersId: '',
      applyStatus: '',
      rejectReason: ''
    },
    rules: {
      dealersId: [{ required: true, message: '请选择经销商', trigger: ['blur', 'change'] }],
      ruleId: [{ required: true, message: '请选择经销商注册规则', trigger: ['blur', 'change'] }],
      productIdList: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(value.length === 0) {
              callback(new Error('请选择绑定商品'))
            } else {
              callback()
            }
          } 
        }
      ],
    },
    productApplyId: '',
    dealersId: '',
    dealerList: [],
    ruleList: [],
    dataList: [],
    bindGoods: [],
    goods: []
  })
  let {loading, show, innerShow, infoShow, query, goodsQuery, form, examineForm, rules, productApplyId, dealersId, dealerList, ruleList, dataList, bindGoods, goods} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getDealerGoodsApplyListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 获取商品申请规则下拉列表
  function loadRules() {
    getGoodsApplyRuleListApi().then(res => {
      if (res.code === '200') {
        currentData.ruleList = res.data
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 获取经销商下拉列表
  function loadDealer(dealerName) {
    if(!dealerName) {
      return
    }
    getDealerListApi({dealerName: dealerName}).then(res => {
      if(res.code === '200') {
        currentData.dealerList = res.data
      }
    })
  }

  // 获取经销商可绑商品数据
  function loadGoods(page) {
    // currentData.goodsQuery.current = page
    // getDealerCanBindGoodsListPagesApi(currentData.goodsQuery).then(res => {
    //   if (res.code === '200') {
    //     currentData.goods = res.data.pages
    //     currentData.goodsQuery.total = res.data.total
    //   } else {
    //     currentThis.$message.error(res.message)
    //   }
    // })
  }

  function toChooseGoods() {
    loadGoods(1)
    currentData.innerShow = true
  }

  // 选择绑定商品
  function doChooseGoods() {
    let chooseGoods = tableRef.value.getSelectionRows()
    if(chooseGoods.length > 0) {
      currentData.bindGoods = chooseGoods
      let goodsIds = []
      currentData.bindGoods.forEach(item => {
        goodsIds.push(item.productId)
      })
      currentData.form.productIdList = goodsIds
      currentData.innerShow = false
    } else {
      currentThis.$message.error('请选择商品')
    }
  }

  // 删除绑定商品
  function doDeleteBindGoods(index) {
    currentData.bindGoods.splice(index, 1)
    let goodsIds = []
    currentData.bindGoods.forEach(item => {
      goodsIds.push(item.productId)
    })
    currentData.form.productIdList = goodsIds
  }

  // 新增经销商商品申请
  function doSave() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm('确认新增吗？').then(() => {
          let loading = currentThis.$loading('正在新增，请耐心等待')
          saveDealerGoodsApplyApi(currentData.form).then(res => {
            loading.close()
            if(res.code === '200') {
              load(1)
              currentData.show = false
              currentThis.$message.success(res.message)
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  function toView(e) {
    currentData.productApplyId = e.productApplyId
    currentData.dealersId = e.dealersId
    currentData.infoShow = true
  }

  // 审核通过或驳回弹窗确认
  function toExamine(e, type) {
    currentData.examineForm = {productApplyId: e.productApplyId, dealersId: e.dealersId, applyStatus: type ? 1 : 2, rejectReason: ''}
    if(type) {
      currentThis.$messageBox.confirm('确认通过吗？').then(() => {
        doExamine()
      }).catch(() => {})
    } else {
      currentThis.$messageBox.prompt('驳回原因', '确认驳回吗？').then(({value}) => {
        currentData.examineForm.rejectReason = value
        doExamine()
      }).catch(() => {})
    }
  }
  // 执行审核
  function doExamine() {
    const loading = currentThis.$loading('正在处理，请耐心等待')
    updateDealerGoodsApplyStatusApi(currentData.examineForm).then(res => {
      loading.close()
      if(res.code === '200') {
        load(currentData.query.current)
        currentThis.$message.success(res.message)
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  function doChose(e) {
    if(e) {
      load(currentData.query.current)
    }
    currentData.infoShow = false
  }
  
  // 重置查询
  function resetSearch() {
    currentData.query.dealersId = ''
    currentData.query.applyStatus = ''
    load(1)
  }

   // 新增弹窗重置数据
  function resetForm() {
    currentData.form = {
      dealersId: '',
      ruleId: '',
      productIdList: []
    }
    currentData.bindGoods = []
    formRef.value.resetFields()
  }

  // 分页每页显示条数改变执行
  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }
  function goodsSizeChange(size) {
    currentData.goodsQuery.size = size
    loadGoods(1)
  }

  onActivated(() => {
    load(currentData.query.current)
    loadRules()
  })
</script>

<style lang="less" scoped>
.dealerGoodsApply{
  :deep(.el-select.custom_select){
    .el-input{
      width: 200px !important;
    }
  }
  :deep(.el-drawer){
    .el-drawer__body{
      padding: 0 20px !important;
    }
  }
  :deep(.el-dialog){
    .el-dialog__body{
      max-height: 500px;
      overflow: hidden auto;
      .el-form-item__content{
        >.el-input{
          width: 300px;
        }
      }
      .img-cell{
        display: flex;
        justify-content: center;
        align-items: center;
        .el-image{
          width: 40px; 
          height: 40px;
          border-radius: 5px;
        }
      }
      .idCard_upload{
        width: 400px; 
        height: 200px;
        border-radius: 8px;
        border: 1px dashed #DCDFE6;
        cursor: pointer;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 100px;
        color: #DCDFE6;
        &:hover{
          border-color: #409EFF;
        }
        span{
          color: #8a8b8b;
        }
      }
    }
  }
}
</style>